package com.company.chatRoom;

import com.company.utils.JSonUtil;
import com.company.utils.MyException;

import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @Auther Xue
 * @Date 2021/4/28
 * @Version 1.0
 * @Desc    心跳包线程
 */
public class ClientHeart implements Runnable {
    private Socket socket;
    private String username;

    //一个socket下的oos只能有一个
    private ObjectOutputStream oos;

    public ClientHeart(Socket socket, String username) {
        this.socket = socket;
        this.username = username;
    }

    @Override
    public void run() {
        try {
            oos = Utils.getOOSBySocket(socket);
            System.out.println("心跳包进程已启动...");
            while (true){
                if(Utils.isServerClose(socket)){
                    socket.close();
                    System.out.println("断开连接");
                    break;
                }
                Thread.sleep(3000);
                Map obj = new HashMap();
                obj.put("type","heart");
                obj.put("msg","心跳包");
                obj.put("user",username);
                oos.writeObject(obj);
                oos.flush();
            }
        } catch (Exception e) {
            MyException.logExceptionMessage(e);
        }finally {
            try {
                socket.close();
                ChatClient.turnOffState();
                ChatClient.reconnect();
            }catch (Exception e){
                MyException.logExceptionMessage(e);
            }
        }
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

}

